<script setup>
import { artEditService, artGetDetailService, artPublishService } from '@/api/article'
import { baseURL } from '@/utils/request'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import axios from 'axios'
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
// 提交
const emit = defineEmits(['success'])
// 控制抽屉的显示隐藏
const visibileDrawer = ref(false)
// 准备数据

// 默认表单数据
const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: '',
}
// 表单数据
const formModel = ref({
  ...defaultForm,
})
const imgUrl = ref('')
function onSelectFile(uploadFile) {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}
async function onPublish(state) {
  formModel.value.state = state
  // 将对象=>转换成=>formData对象
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  if (formModel.value.id) {
    // 编辑
    // console.log('编辑')
    await artEditService(fd)
    // eslint-disable-next-line no-undef
    ElMessage.success('修改成功')
    visibileDrawer.value = false
    emit('success', 'edit')
  }
  else {
    // 添加操作
    await artPublishService(fd)
    // eslint-disable-next-line no-undef
    ElMessage.success('添加成功')
    visibileDrawer.value = false
    // 通知父组件，添加成功
    emit('success', 'add')
  }
}
const editorRef = ref()
async function open(row) {
  visibileDrawer.value = true
  if (row.id) {
    const res = await artGetDetailService(row.id)
    formModel.value = res.data.data
    // 图片需要单独处理
    imgUrl.value = baseURL + formModel.value.cover_img
    // 注意：提交给后台，需要的数据格式，是file对象格式
    // 需要将网络图片地址=>转换成file对象，存储起来
    const file = await imageUrlToFile(imgUrl.value, formModel.value.cover_img)
    formModel.value.cover_img = file
    // console.log(formModel)
  }
  else {
    formModel.value = { ...defaultForm } // 基于默认的数据，重置数据
    imgUrl.value = ''
    editorRef.value.setHTML('')
  }
}
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  }
  catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
defineExpose({
  open,
})
</script>

<template>
  <el-drawer
    v-model="visibileDrawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <ChannelSelect
          v-model="formModel.cate_id"
          width="100%"
        />
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 此处需要关闭element-plus 的自动上传，不需要配置 action等参数
         只需要做前端的本地预览图片即可，无需在提交前上传图标
         语法：URL.createObjectURL(...)创建本地预览的地址，来预览 -->
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onSelectFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar">
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <QuillEditor ref="editorRef" v-model:content="formModel.content" content-type="html" theme="snow" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">
          发布
        </el-button>
        <el-button type="info" @click="onPublish('草稿')">
          草稿
        </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      display: block;
      width: 178px;
      height: 178px;
    }

    .el-upload {
      position: relative;
      overflow: hidden;
      cursor: pointer;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      width: 178px;
      height: 178px;
      font-size: 28px;
      color: #8c939d;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
